<?php
declare (strict_types=1);

namespace app\index\controller;

use app\common\model\OrderTemporary;
use app\common\model\ProductCart;
use app\common\model\Product as ProductModel;
use app\common\model\ProductCate;
use app\common\model\ProductSpec;
use app\common\tool\Result;
use think\facade\Cache;
use think\facade\View;
use think\Response;

class Product extends Base
{
    public function search(): string
    {
        $history = Cache::get('searchHistory_' . $this->user->id);
        if ($history) {
            $history = json_decode($history, true);
            $news = [];
            for ($i = count($history); $i > 0; $i--) {
                $news[] = $history[$i - 1];
            }
            $history = $news;
        }
        View::assign('history', $history ?: []);

        return View::fetch();
    }

    public function clearSearch(): Response
    {
        Cache::delete('searchHistory_' . $this->user->id);

        return Result::success('已清空');
    }

    public function index(): string
    {
        $cate_1 = $this->request->get('cate_1');
        $cate_2 = $this->request->get('cate_2', $cate_1);
        $keyword = $this->request->get('keyword');
        $cate = ProductCate::where(['id' => $cate_2])->value('title');
        View::assign([
            'title' => $keyword ?: $cate,
            'cate_1' => $cate_1,
            'keyword' => $keyword
        ]);

        return View::fetch();
    }

    public function getList(): Response
    {
        $param = $this->request->get();
        $map = [];
        foreach ($param as $key => $value) {
            if (!in_array($key, ['type', 'keyword', 'filed', 'sort', 'page', 'limit']) && $value) {
                $map[$key] = $value;
            }
        }
        $like = [];
        if (!empty($param['keyword'])) {
            $like['field'] = 'title';
            $like['keyword'] = trim($param['keyword']);
            $this->verifyToken();
            if ($this->user) {
                $history = Cache::get('searchHistory_' . $this->user->id);
                if ($history) {
                    $history = json_decode($history, true);
                    if (!in_array($param['keyword'], $history)) {
                        $history[] = $param['keyword'];
                        Cache::set('searchHistory_' . $this->user->id, json_encode($history));
                    }
                } else {
                    $history[] = $param['keyword'];
                    Cache::set('searchHistory_' . $this->user->id, json_encode($history));
                }
            }
        }
        if (!empty($param['filed']) && !empty($param['sort'])) {
            $sort[] = ['key' => $param['filed'], 'value' => $param['sort']];
        }
        $sort[] = ['key' => 'sort', 'value' => 'desc'];
        $sort[] = ['key' => 'id', 'value' => 'asc'];

        return Result::fastReturn(ProductModel::getPageList($map, 'id,title,price,vip_price,icon,sales,stock',
            $this->getPage(), $this->getLimit(), true, [], [], $sort, $like));
    }

    public function details($id): string|Response
    {
        $info = ProductModel::where(['id' => $id, 'status' => 1])->find();
        if (empty($info)) return redirect('/');
        $info->images = $info->images ? explode(',', $info->images) : '';
        $this->verifyToken();
        if ($this->user) {
            $cart_num = ProductCart::where('uid', $this->user->id)->count();
        } else {
            $cart_num = 0;
        }
        View::assign([
            'info' => $info,
            'count' => $cart_num
        ]);

        return View::fetch();
    }

    public function getSpecInfo($pid, $spec): Response
    {
        $specValue = ProductSpec::where(['pid' => $pid, 'merge_title' => $spec])->find();
        if (empty($specValue)) {
            return Result::fail('当前规格已下架！');
        }
        $specValue->icon = $specValue->icon ?: $specValue->product->icon;
        unset($specValue->product);

        return Result::success('success', $specValue);
    }

    public function submit(): Response
    {
        $param = $this->request->post();
        $param['type'] = 1;

        return Result::fastReturn(OrderTemporary::setTemporary($param, $this->user));
    }
}